//app.js
const core = require('utils/core');
const EventBus = require('utils/eventbus');
const chatIM = require('utils/websocket.js');
App({
  device_statusBarHeight: wx.getSystemInfoSync().statusBarHeight,
  onLaunch: function () {
    this.getIsIPhoneX().then(isIPhoneX => {
      this.globalData.isIPhoneX = isIPhoneX;
    });
    let app = this;
    core.onRequestComplete(function (ret, response) {
      if(ret && ret.code===401) {
        if(app.getUserinfo()) {
          app.logout();
          wx.navigateTo({url: '/pages/change/change'});
          wx.showToast({title: '登录过期,请重新登录',icon:'none'});
        }
      }
    });
    setTimeout(function () {
       // app初始化完成后再执行
	   let userinfo = app.getUserinfo();
	   if (userinfo) {
		   	app.globalData.userinfo =  userinfo;
			chatIM.connectSocket();
	   }
    },1);
  },
  onShow: function() {
	
  },
  globalData: {
    isIPhoneX: null,
    //以下为小程序配置 必填wx6db*******cc2dcf
    appid: "",
	  //小程序配置的接口请求域名，为项目部署的服务器路径 参考形式
	  wsDomain: 'wss://www.example.com:8282',
    apiBaseUri: "https://www.example.com/api",

    //以下为图片存储配置 建议存储到OSS，
    uploadOssStatus:false,//是否开启oss上传 false or true，不开启无需配置OSS参数
    storageBaseUri: "",//必填，前端上传图片补全域名，如oss的https://xxxx.oss-cn-shanghai.aliyuncs.com，或https://your.site.com
    alioss: {endpoint:''}, //阿里OSS的上传路径，uploadOssStatus为false无需填写,为true必填

    //网站：https://lbs.qq.com 注册登录并创建应用
    //mapSdkKey(T5YBZ-LHOWJ-***********-WSO5V-LXBAI)与mapSdkSk(vbbcPaYT73sv**********xZPlsSGi)创建：对应的应用里创建key，创建key时勾选WebServiceAPI,并勾选里面的签名校验
    //mapSdkKey对应 Key,mapSdkSk对应Secret key（ SK ）
    //用图：求职者在面试邀请里地址导航
    mapSdkKey: '',
    mapSdkSk: '',
    //默认城市
	defaultCity: {id:802, name:'上海'},
	userinfo:null,
	chat_config: {
		SocketTask: null,
		Timer: null,
		ErrorMsg: [],
		MaxRetryCount: 30, // 最大重连次数
		CurrentRetryCount: 0,
		ortherdata: null, //其他通用数据
		emoList:[], //表情
		messageCount:0, //未读消息数
	},

  },
  Events: {
    UserLogin: "userLogin",
	UserLogout: "userLogout",
	UserinfoChange: 'userinfoChange',
    WxAccountUpdate: "wxAccountUpdate",
    UserinfoUpdate: "userinfoUpdate",
    UserProfileUpdate: "userProfileUpdate",
    UcenterInfoCompleteChange: "ucenterInfoCompleteChange",
    CurrentCityChange: 'currentCityChange',
    JobCreate: "jobCreate",
    JobUpdate: "jobUpdate",
    JobDelete: "jobDelete",
    InterviewCommentAdd: "interviewCommentAdd",
    ResumeFavAdd: "resumeFavAdd",
    ResumeFavRemove: "resumeFavRemove",
    CompanyFavRemove: "companyFavRemove",
    CompanyFavAdd: "companyFavAdd",
    JobFavAdd: "jobFavAdd",
    JobFavRemove: "jobFavRemove",
    ClearMessageCount: "clearMessageCount",
	RefreshUserCenter: "refreshUserCenter", //设置refresh标记，回到usercenter后刷新页面
	WebsocketMessageCount: 'WebsocketMessageCount'
  },
  eventBus: new EventBus(),
  // 获取当前登录用户信息
  getUserinfo(forceLogin = false) {
    let userinfo = core.getCache('userinfo');
    if (!userinfo && forceLogin){
      wx.navigateTo({
        url: '/pages/change/change',
      });
      return false;
    }
    return userinfo;
  },
  setUserinfo(user) {
    if(!user) {
      throw "不能设置空值";
    }
    core.setCache('userinfo', user);
    this.eventBus.emit(this.Events.UserinfoUpdate, user);
  },
  //登出
  logout() {
    core.removeCache('userinfo');
    this.eventBus.emit('userLogout');
  },
  //获取定位
	getLocation(){
		var page = this;
		wx.getLocation({
			type: 'gcj02',
			success: function (res) {
				page.getCityByLat(res.latitude,res.longitude)
			},
			fail: function(res){
				console.log(res);
				page.setCurrentCity(page.getCurrentCity());
			}
		});
	},
	getCityByLat(lat,lng){
		let app = this;
		core.post({url: 'xilujob.common/get_city_by_lat',loading: false,data: {lat: lat,lng: lng},success: (ret, response) => {
			let city = app.getCurrentCity();
			if(city.id != ret.data.id){
				wx.showModal({
				  title: '定位切换',
				  content: '当前定位城市为'+ret.data.name+',是否切换城市？',
				  complete: (res) => {
					if (res.confirm) {
						app.setCurrentCity(ret.data);
					}
				  }
				})
			}
			
		},
		fail: (ret, response) => {
				this.setCurrentCity(this.getCurrentCity());
				return false;
		}
		});
	},
   // 静默获取openid, 然后从服务器拉取wx_account信息
   wxLogin(cb) {
    let app = this;
    function executeLogin() {
      wx.login({
        success(wxRes) {
          let code = wxRes.code;
          core.post({
            url: '/xilujob.user/wxlogin',
            data: {code: code},
            success: (ret, response) => {
              let third = ret.data.third;
              core.setCache('wx_account', third);
              if(third.binding == 1) {
				  app.setUserinfo(ret.data.userinfo);
				  typeof cb == 'function' && cb()
			  }
              
            },fail: (ret, response) => {
			  //失败，重试
			  wx.showModal({
				title: '提示',
				content: ret.msg,
				showCancel:false,
				complete: (res) => {
				  if (res.confirm) {
					wx.navigateBack();
				  }
				}
			  })
            //   setTimeout(function(){
            //     executeLogin();
            //   },60000);
              return false;
            }
          });
        },
      });
    }
    if(!this.getWxAccount()) {
      executeLogin();
      return;
    }
    wx.checkSession({
	  success(){
		executeLogin();
	  },
      fail(){
        executeLogin();
      }
    });
  },
  // 获取包含openid及其它微信用户信息
  getWxAccount() {
    return core.getCache('wx_account', null);
  },

  getCache(key, defaultValue) {
    return core.getCache(key, defaultValue);
  },
  setCache(key, value, expireTimeInSeconds) {
    return core.setCache(key, value, expireTimeInSeconds);
  },
  removeCache(key) {
    return core.removeCache(key);
  },
  getCurrentCity() {
    return core.getCache('current_city', this.globalData.defaultCity);
  },
  /**
   * 设置当前城市
   * @param {object} city 结构应该与globalData.defaultCity一致
   */
  setCurrentCity(city) {
    core.setCache('current_city', city);
    this.eventBus.emit(this.Events.CurrentCityChange, city);
  },



  getIsIPhoneX: function () {
    let isIPhoneX = this.globalData.isIPhoneX;
    return new Promise((resolve, reject) => {
      if (isIPhoneX !== null) {
        resolve(isIPhoneX);
      }
      else {
        wx.getSystemInfo({
          success: ({ model, screenHeight }) => {
            const iphoneX = /iphone x/i.test(model);
            const iphoneNew = /iPhone11/i.test(model);
            isIPhoneX = iphoneX || iphoneNew;
            resolve(isIPhoneX);
          },
          fail: reject
        });
      }
    });
  },
});
